﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Data.SQLite;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        bool editando;

        public Form2()
        {
            InitializeComponent();
        }

        public void cria()
        {
            txtId.Text="";
            txtApto.Text = "";
            txtMsg.Text = "";
            ckAtivo.Checked = true;
            editando = false;
            this.ShowDialog();
        }

        public void edita(string id)
        {
            SQLiteCommand command = new SQLiteCommand("SELECT id,apto,msg,ativo FROM rfid WHERE id='"+id+"'", Form1.db);
            SQLiteDataReader reader = command.ExecuteReader();
            if (reader.HasRows)
            {
                reader.Read();
                txtId.Text = reader["id"].ToString();
                txtApto.Text = reader["apto"].ToString();
                txtMsg.Text = reader["msg"].ToString();
                if (reader["ativo"].ToString() == "1") ckAtivo.Checked = true; else ckAtivo.Checked = false;
                btSalvar.Enabled = false;
                editando = true;
                this.ShowDialog();
            }
        }

        private void btSalvar_Click(object sender, EventArgs e)
        {
            if (txtId.Text.Length != 8 || txtApto.Text == "" || txtMsg.Text == "")
            {
                MessageBox.Show("Registro com erros, verifique e tente novamente.");
            }
            else
            {
                string sql;
                if (editando) sql = "UPDATE rfid SET apto=" + txtApto.Text + ",msg='" + txtMsg.Text + "',ativo=" + (ckAtivo.Checked ? "1" : "0") + " WHERE id='" + txtId.Text + "'";
                else sql = "INSERT INTO rfid (id,apto,msg,ativo) VALUES (" + txtId.Text + "," + txtApto.Text + ",'" + txtMsg.Text + "'," + (ckAtivo.Checked ? "1" : "0") + ")";

                SQLiteCommand command = new SQLiteCommand(sql, Form1.db);
                command.ExecuteNonQuery();
                btSalvar.Enabled = false;
            }
        }

        private void ckAtivo_CheckedChanged(object sender, EventArgs e)
        {
            btSalvar.Enabled = true;
        }

        private void txtApto_TextChanged(object sender, EventArgs e)
        {
            btSalvar.Enabled = true;
        }

        private void txtMsg_TextChanged(object sender, EventArgs e)
        {
            btSalvar.Enabled = true;
        }

        private void txtApto_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && e.KeyChar != (char)8)
            {
                e.Handled = true;
            }
        }
    }
}
